package com.ustc.hewei.rpc.common.Utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.ustc.hewei.rpc.common.protocol.NotifyMessage;
import com.ustc.hewei.rpc.common.protocol.RequestWarp;
import com.ustc.hewei.rpc.common.protocol.ResponseWarp;

import java.io.*;

/**
* @description: 请求和响应的序列化工具类
* @author hewei
* @date 2022/7/25 20:35
* @version 1.0
*/

public class MessageSerialize {
    /*
     * @description: 将对象序列化成字节数组，使用fastJSON进行序列化
     * @param obj 需要序列化的对象，一般为请求或者是响应
     * @return byte[]
     * @author: hewei
     * @date: 2022/7/25 21:04
     **/
    public static byte[] objectToByteArray(Object obj) {
//        ByteArrayOutputStream out = new ByteArrayOutputStream();
//        ObjectOutputStream objectOut = new ObjectOutputStream(out);
//        objectOut.writeObject(obj);
//        return out.toByteArray();
        return JSON.toJSONBytes(obj);
    }

    public static ResponseWarp byteArrayToResp(byte[] data) {
        //return (ResponseWarp) new ObjectInputStream(new ByteArrayInputStream(data)).readObject();
        return JSON.parseObject(data, ResponseWarp.class);
    }

    public static RequestWarp byteArrayToRequest(byte[] data) {
//        ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(data));
//        return (RequestWarp) objectIn.readObject();
        return JSON.parseObject(data, RequestWarp.class, JSONReader.Feature.SupportClassForName);
    }

    public static NotifyMessage byteArrayToNotify(byte[] data) {
        return JSON.parseObject(data, NotifyMessage.class, JSONReader.Feature.SupportClassForName);
    }
}
